package org.chen.config;

import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.ApiListingScannerPlugin;
import springfox.documentation.spi.service.contexts.DocumentationContext;
import springfox.documentation.spring.web.readers.operation.CachingOperationNameGenerator;

import java.util.*;

//@Component
public class SwaggerLoginApiConfig
        implements ApiListingScannerPlugin {

    @Override
    public List<ApiDescription> apply(DocumentationContext context) {
        Set<String> consumeSet = new TreeSet<>();
        consumeSet.add(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        Set<String> producesSet = new TreeSet<>();
        producesSet.add(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        Set<String> tagSet =new TreeSet<>();
        tagSet.add("登录");
        Operation usernamePasswordOperation = new OperationBuilder(new CachingOperationNameGenerator())
                .method(HttpMethod.POST)
                .summary("用户名密码登录")
                .notes("username/password登录")
                .consumes(consumeSet) // 接收参数格式
                .produces(producesSet) // 返回参数格式
                .tags(tagSet)
                .requestParameters(Arrays.asList(
                        new RequestParameterBuilder()
                                .description("用户名")
                                .in("String")
                                .in(ParameterType.BODY)
                                .name("username")
                                .required(true)
                                .build(),
                        new RequestParameterBuilder()
                                .description("密码")
                                .in("String")
                                .in(ParameterType.BODY)
                                .name("password")
                                .required(true)
                                .build()
                ))
                .responses(Collections.singleton(
                       new ResponseBuilder().code("200").description("请求成功")
                               .build()))
                .build();

        ApiDescription loginApiDescription = new ApiDescription("login", "/login", "登录接口",
                "表单请求post",Arrays.asList(usernamePasswordOperation), false);

        return Arrays.asList(loginApiDescription);

    }

    @Override
    public boolean supports(DocumentationType documentationType) {
        return DocumentationType.SWAGGER_2.equals(documentationType);
    }
}
